package com.fly.web.controller;

import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.fly.core.utils.SpringContextUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@RestController
@Api(tags = "测试WebClient1")
public class WebClient1Controller
{
    WebClient webClient;
    
    @PostConstruct
    @DependsOn("springContextUtils")
    public void init()
    {
        try
        {
            log.info("init");
            String baseUrl = SpringContextUtils.getServerBaseURL();
            this.webClient = WebClient.builder().codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)).baseUrl(baseUrl).build();
        }
        catch (UnknownHostException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @GetMapping("/get01")
    public String get()
        throws InterruptedException
    {
        TimeUnit.MILLISECONDS.sleep(1000L);
        return "get";
    }
    
    @ApiOperation("测试")
    @GetMapping("/get")
    public Mono<String> hello()
    {
        return webClient.get().uri("/get").exchange().flatMap(clientResponse -> clientResponse.bodyToMono(String.class));
    }
    
    @ApiOperation("测试csdn")
    @GetMapping("/csdn")
    public Mono<String> csdn()
    {
        Mono<String> result = webClient.get()
            .uri("https://blog.csdn.net/qq_16127313/article/details/{id}", 144355710)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .acceptCharset(StandardCharsets.UTF_8)
            .accept(MediaType.TEXT_HTML)
            .retrieve()
            .bodyToMono(String.class);
        return result;
    }
}
